﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NDepot.Models;
using NDepot.Repository.Base;

namespace NDepot.Repository
{
    public class ProductRepository : IProductRepository
    {
        private DepotDataContext _dataContext;

        public ProductRepository()
        {
            _dataContext = new DepotDataContext();
        }

        #region IProductRepository Members

        public Product GetById(Guid id)
        {
            return _dataContext.Products.Single(p => p.Id == id);
        }

        public void Insert(Product entity)
        {
            _dataContext.Products.InsertOnSubmit(entity);
            _dataContext.SubmitChanges();
        }

        public void Update(Product entity)
        {
            _dataContext.SubmitChanges();
        }

        public IList<Product> GetAll()
        {
            var products = from p in _dataContext.Products
                           orderby p.Title
                           select p;
            return products.ToList();
        }

        public bool Delete(Product entity)
        {
            try
            {
                _dataContext.Products.DeleteOnSubmit(entity);
                _dataContext.SubmitChanges();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public void DeleteAll()
        {
            _dataContext.Products.DeleteAllOnSubmit(GetAll());
            _dataContext.SubmitChanges();
        }

        public IList<Product> FindProductsForSale()
        {
            var products = from p in _dataContext.Products
                           orderby p.Title
                           select p;
            return products.ToList();
        }

        #endregion

        public Product GetByTitle(string Title)
        {
            var product = from p in _dataContext.Products
                           where p.Title == Title
                           select p;
            if (product.Count() > 0)
                return product.Single();

            return null;
        }

        public IList<Order> GetOrdersByProduct(Product product)
        {
            var orders = from lineitem in _dataContext.LineItems
                         where lineitem.ProductId == product.Id
                         select lineitem.Order;

            return orders.ToList<Order>();
        }
    }
}